package org.tacticalTroopers.jme.server.score;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.tacticalTroopers.jme.common.message.Information;
import org.tacticalTroopers.jme.server.TacticalTroopersServer;
import org.tacticalTroopers.jme.server.object.ServerBullet;
import org.tacticalTroopers.jme.server.object.ServerElement;
import org.tacticalTroopers.jme.server.object.ServerPlayer;
import org.tacticalTroopers.jme.server.team.Team;
import org.tacticalTroopers.jme.server.team.TeamManager;

public class ScoreManager {

	private static final String SCORE = "Score";
	List<ServerPlayer> players = new ArrayList<ServerPlayer>();
	TeamManager teamManager;

	Map<ServerPlayer,Score> playerToScore = new HashMap<ServerPlayer,Score>();
	Map<Team,Score> teamToScore = new HashMap<Team,Score>();

	TacticalTroopersServer tacticalTrooperServer;
	public ScoreManager(TacticalTroopersServer tacticalTrooperServer) {
		this.tacticalTrooperServer = tacticalTrooperServer;
	}

	public void setTeamManager(TeamManager teamManager) {
		this.teamManager=teamManager;
	}
	
	public void playerHit(ServerPlayer shooter, ServerElement victim, ServerBullet bullet) {
		getScore(shooter).addPoint();
		sendScore();
	}

	public void playerHit(ServerPlayer shooter, ServerPlayer victim, ServerBullet bullet) {
		/*
		if(victim.getState()==ServerPlayer.State.LIVE){
			if(!teamManager.belongToSameTeam(shooter,victim)){
			}
		}
		 
		 */
				getScore(shooter).addPoint();
				getScore(teamManager.getTeam(shooter)).addPoint();
				sendScore();

	}
	
	void sendScore(){
		StringBuffer sb = new StringBuffer();
		for(ServerPlayer player : playerToScore.keySet()){
			sb.append(tacticalTrooperServer.getPlayerManager().getName(player.getId().getValue()));
			sb.append(":");
			sb.append(playerToScore.get(player).getValue());
			sb.append("\n");
		}
		sb.append("\n");
		for(Team team : teamToScore.keySet()){
			sb.append("Team"+team.getId());
			sb.append(":");
			sb.append(teamToScore.get(team).getValue());
			sb.append("\n");
		}
		
		tacticalTrooperServer.addToInformationQueue(new Information().setKey(SCORE).setValue(sb.toString()));
	}

	public void add(ServerPlayer player) {
		players.add(player);
		playerToScore.put(player, new Score());
	}

	public void remove(ServerPlayer player) {
		players.remove(player);
		playerToScore.remove(player);
	}

	public Score getScore(ServerPlayer player) {
		return playerToScore.get(player);
	}

	public Score getScore(Team team) {
		if(teamToScore.get(team)==null){
			teamToScore.put(team, new Score());
		}
		return teamToScore.get(team);
	}

}
